package list;

import java.util.Iterator;

/**
 * @Auther: liwenhao
 * @Date: 2022/5/12 11:11
 * @Description:
 */
public class LinkList<T> implements Iterable<T> {

    //头结点
    private Node<T> head;

    //链表长度
    private volatile int N;

    public LinkList() {
        head = new Node(null, null);
        N = 0;
    }

    //空置链表
    public void clear(){
        head.next = null;
        head.item = null;
        N  = 0;
    }

    //判断是否为空
    public boolean isEmpty(){
        return N == 0;
    }

    //链表长度
    public int length(){
        return N;
    }

    // 返回第I个元素
    public T get(int i){
        if (i < 0 || i > N) {
            throw new RuntimeException("位置不合法！");
        }
        Node<T> n = head.next;
        for (int index = 0; index < i; index++) {
            n = n.next;
        }
        return n.item;
    }
    //链表中添加元素
    public void insert(T t){
        Node node = head.next;
        while (node.next != null){
            node = node.next;
        }
        Node newNode = new Node(t, null);
        node.next = newNode;
        N++;
    }

    public void insert(int i, T t){
        if (i < 0 || i > N) {
            throw new RuntimeException("位置不合法！");
        }
        Node pre = head;
        for (int index = 0; index <= i-1; index++) {
            pre = pre.next;
        }
        Node cur = pre.next;
        Node newNode = new Node(t, cur);
        pre.next = newNode;
        N++;
    }

    public T remove(int i){
        if (i < 0 || i > N) {
            throw new RuntimeException("位置不合法！");
        }
        Node<T> pre = head;
        for (int index = 0; index <= i-1; index++) {
            pre = pre.next;
        }
        Node<T> cur = pre.next;
        pre.next = cur.next;
        N--;
        return cur.item;
    }

    public int indexOf(T t){
        Node n = head;
        for (int i = 0;n.next!=null;i++){
            n = n.next;
            if (n.item.equals(t)) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public Iterator<T> iterator() {
        return new LIterator();
    }

    private class LIterator implements Iterator<T>{
        private  Node<T> n;

        public LIterator() {
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public T next() {
            n = n.next;
            return n.item;
        }
    }

    public class Node<T> {

        T item;

        Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
}
